package com.aixin.project.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aixin.project.util.AxUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

import com.aixin.project.data.AxSession;
import com.aixin.project.data.CommonConstants;
import com.aixin.project.data.Expert;
import com.aixin.project.data.User;
import com.aixin.project.data.UserType;
import com.aixin.project.handler.ExpertHandler;
import com.aixin.project.handler.UserHandler;
import com.aixin.project.util.RequestUtil;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 12-4-9 Time: 上午3:20 To
 * change this template use File | Settings | File Templates.
 */
public abstract class BaseServlet extends VelocityViewServlet {
	Logger logger = Logger.getLogger(BaseServlet.class);

    protected void before(HttpServletRequest request,
                          HttpServletResponse response, Context ctx) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String MESSAGE = (String) request.getSession().getAttribute("MESSAGE");
        String ERROR = (String) request.getSession().getAttribute("ERROR");
        if(StringUtils.trimToNull(MESSAGE)!=null){
            ctx.put("MESSAGE",MESSAGE);
            request.getSession().removeAttribute("MESSAGE");
        }
        if(StringUtils.trimToNull(ERROR)!=null){
            ctx.put("ERROR",ERROR);
            request.getSession().removeAttribute("ERROR");
        }
        AxSession axsession = (AxSession) request.getSession().getAttribute(CommonConstants.USER_SESSION);
        if (axsession == null) { //try to load user session from cookie
            String u = RequestUtil.getCookie("u", request);
            if (StringUtils.trimToNull(u) != null) {
                String[] sarr = u.split("_");
                if (sarr.length == 2) {
                    if ("u".equals(sarr[0])) { //user cookie
                        long uid = NumberUtils.toLong(sarr[1], -1);
                        User user = UserHandler.find(uid);
                        if (user != null) {
                            axsession = new AxSession(UserType.USER, uid, true, RequestUtil.getGenseeUid(request,response));
                            request.getSession().setAttribute(CommonConstants.USER_SESSION, axsession);
                        }
                    } else if ("e".equals(sarr[0])) { //export cookie
                        long eid = NumberUtils.toLong(sarr[1], -1);
                        Expert expert = ExpertHandler.find(eid);
                        if (expert != null) {
                            axsession = new AxSession(UserType.EXPERT, eid, true,RequestUtil.getGenseeUid(request,response));
                            request.getSession().setAttribute(CommonConstants.USER_SESSION, axsession);
                        }
                    }
                }
            }
        }
        if(axsession != null){
            if(axsession.getUserType().equals(UserType.USER)){
                User user = UserHandler.find(axsession.getUid());
                if(user != null)
                    ctx.put("USER",user);
            }else if(axsession.getUserType().equals(UserType.EXPERT)){
                Expert expert = ExpertHandler.find(axsession.getUid());
                if(expert!=null)
                    ctx.put("USER",expert);
            }
            ctx.put("AXSESSION",axsession);
            AxUtil.setThreadLocalAxSession(axsession);
        }
        AxUtil.setThreadLocalRequest(request);
    }

    protected void after(HttpServletRequest request,
                         HttpServletResponse response, Context ctx) {
    }

    protected Template handleRequest(HttpServletRequest request,
                                     HttpServletResponse response, Context ctx) {
        long start = System.currentTimeMillis();
        /* before page excute, do something */
        before(request, response, ctx);
        Template template = execute(request, response, ctx);
        /* after page excute, do something */
        after(request, response, ctx);
        long end = System.currentTimeMillis();
        System.out.println(request.getPathInfo()+" page execute time :" + (end - start));
        return template;
    }

    protected abstract Template execute(HttpServletRequest request,
                                        HttpServletResponse response, Context ctx);

    protected void mergeTemplate(Template template, Context context,
                                 HttpServletResponse response)
            throws IOException {
        if (null != template)
            super.mergeTemplate(template, context, response);
    }

    protected void sendRedirect(HttpServletResponse response,String url){
    	try {
			response.sendRedirect(url);
		} catch (IOException e) {
			logger.error("redirect url error: "+url);
		}
    }

}
